package org.zjt.agent.runtime;

import org.zjt.agent.runtime.reloader.ClassReloader;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;

/**
 * Description:
 *
 *     加载新的class 时候才会调用该方法
 *
 * @author juntao.zhang
 * Date: 2018-10-24 2:21 PM
 * @see
 */
public class RuntimeClassTransformer implements ClassFileTransformer {

    private static final Logger LOGGER = Logger.getLogger(ClassFileTransformer.class.getName());

    private ClassFileTransformer classFileTransformer;

    private final List<ClassReloader> classReloaders;

    public RuntimeClassTransformer(ClassFileTransformer classFileTransformer, List<ClassReloader> classReloaders) {
        this.classFileTransformer = classFileTransformer;
        this.classReloaders = classReloaders;
    }

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

        LOGGER.info("RuntimeClassTransformer:"+className+"  "+ className.contains("ValidateController"));
        Optional<byte[]> bytesOp = classReloaders.stream().map(item -> item.redefineClass(className,classfileBuffer)).filter(Optional::isPresent).map(Optional::get).findAny();
        if (bytesOp.isPresent()){
            return bytesOp.get();
        }
        return classFileTransformer.transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
    }

}
